package server;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;

/*
* 这个类是用于新建连接的
* */
public class CheckConn extends Thread{
    public ArrayList<HandleConn> conns=new ArrayList<HandleConn>();
    public static boolean acceptRush=false;
    public static long startTime=0;
    @Override
    public void run(){
        Out.say("Starting listener.");
        ServerSocket serverSocket=null;
        try {
            serverSocket = new ServerSocket(ServerMain.PORT);
        }catch(Exception e){
            Out.say("[ERR]Create Listener failed:"+e.getStackTrace());
            System.exit(-1);
        }
        while(true){
            try {
                //新连接
                Socket socket=serverSocket.accept();
                //BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                //bufferedWriter.write("time "+(new Date().getTime()));
                //bufferedWriter.write("rushserver");
                //bufferedWriter.newLine();
                //bufferedWriter.flush();
                //bufferedWriter.close();
                HandleConn handleConn=new HandleConn(socket);
                handleConn.start();
                Out.say("New Conn accepting.");
                this.conns.add(handleConn);
                ServerMain.mf.repaint();
            } catch (IOException e) {
                Out.say("[ERR]Accept a conn failed.");
                e.printStackTrace();
            }
        }
    }
/*
* 时间到，计算谁是抢到的
* */
    public void computeFirstRusher(){
        long min=9223372036854775807l;
        for(HandleConn conn:this.conns){
            //犯规的判定已写在实时
            //如果为-1则跳过
            Out.say("  "+conn.clientId+" "+conn.rushtime);
            if(conn.rushtime==-1||conn.rushtime==-2){
                continue;
            }
            //计算最小值
            if(conn.rushtime<min){
                min=conn.rushtime;
                ServerMain.mf.panel.idToDisplay=conn.clientId;
                ServerMain.mf.panel.stateStr="开始后的延迟是统计选手的抢答信息并进行比较";//+(conn.rushtime-CheckConn.startTime);
            }
        }
        ServerMain.mf.repaint();
    }
}
